# 超时处理控制的中间件
import threading
import signal
from django.http import HttpResponseServerError

# class TimeoutMiddleware:
#     def __init__(self, get_response):
#         self.get_response = get_response
#
#     def __call__(self, request):
#         # 注册信号处理函数
#         # signal.signal(signal.SIGALRM, self.timeout_handler)
#         signal.signal(signal.SIGALRM, self.timeout_handler)
#         # 设置超时时间为10秒
#         signal.alarm(10)  # 设置超时时间（以秒为单位）
#
#         try:
#             response = self.get_response(request)
#         except TimeoutError:
#             response = HttpResponseServerError("Request Timeout")
#         finally:
#             # 取消超时设置
#             signal.alarm(0)  # 重置信号
#
#         return response
#
#     def timeout_handler(self, signum, frame):
#         raise TimeoutError("Request timeout")



class WinTimeoutMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        timeout = 5  # 设置超时时间（以秒为单位）

        timer = threading.Timer(timeout, self.timeout_handler)
        timer.start()

        try:
            response = self.get_response(request)
        except TimeoutError:
            response = HttpResponseServerError("Request Timeout")
        finally:
            timer.cancel()

        return response

    def timeout_handler(self):
        raise TimeoutError("Request timeout")

class ResponseTimeoutMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 设置响应超时时间（以秒为单位）
        timeout = 5

        response = self.get_response(request)
        response['X-Content-Duration'] = str(timeout)  # 将超时时间添加到响应头

        return response